package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.KGXAddData;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.ui.adapter.KGXAddAdapter;
import com.qiantu.phone.ui.adapter.TLPKGXAdapter;
import com.qiantu.phone.ui.dialog.BottomKGXCollectionTypeCountDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;

public class KGXAddActivity extends AppActivity {
    private RecyclerView recyclerView;
    private KGXAddAdapter adapter;
    private String controllerSerialNo;
    private int currentNumCount;
    //个数选择
    private BottomKGXCollectionTypeCountDialog typeCountDialog;
    List<KGXAddData> addData;

    public static void start(Context context, String controllerSerialNo, int currentNumCount) {
        Intent intent = new Intent(context, KGXAddActivity.class);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        intent.putExtra("currentNumCount", currentNumCount);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId(){
        return R.layout.activity_kgx_add;
    }

    @Override
    public void onRightClick(View view) {
        saveAction();
    }

    @Override
    protected void initView(){
        controllerSerialNo = getString("controllerSerialNo");
        currentNumCount = getInt("currentNumCount");
        recyclerView = findViewById(R.id.load_device_recycler_view);
        LinearLayoutManager linearLayout = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayout);
        adapter = new KGXAddAdapter(this);
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {

                int totalSum = 0;
                for (KGXAddData data : addData) {
                    totalSum += data.getNum();
                }

                if (totalSum>24){
                    //超过提醒
                }else {
                    showCountialog(position,24-totalSum-currentNumCount);
                }
            }
        });
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData(){
        LLHttpManager.getdevicecollectlistbybrand(this, controllerSerialNo,1, 4508, new HttpCallback<HttpData<List<KGXAddData>>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<List<KGXAddData>> result) {
                super.onSucceed(result);
                addData = result.getData();
                adapter.setData(addData);
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private void showCountialog(int index,int totalSum) {
        KGXAddData currentData = addData.get(index);
        totalSum = totalSum + currentData.getNum();
        if (typeCountDialog == null) {
            typeCountDialog = new BottomKGXCollectionTypeCountDialog(this);
        }
            typeCountDialog.setDialogClickListener(new BottomKGXCollectionTypeCountDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String count) {
                    typeCountDialog.dismiss();
                    //刷新视图
                    currentData.setNum(Integer.parseInt(count));
                    adapter.notifyItemChanged(index);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(typeCountDialog);

        List<String> numbers = new ArrayList<>();
        for (int i = 1; i <= totalSum; i++) {
            numbers.add(String.valueOf(i));
        }
        typeCountDialog.setCounts(numbers);
        int currentCount = currentData.getNum();
        if (currentCount == 0){
            currentCount = 1;
        }
        typeCountDialog.setSelected(String.valueOf(currentCount));
        typeCountDialog.show();
    }

    private void saveAction(){

        List<KGXAddData> filteredData = new ArrayList<>();
        for (KGXAddData data : addData) {
            if (data.getNum() != 0) {
                filteredData.add(data);
            }
        }
        // 如果需要转换成数组
        KGXAddData[] filteredArray = filteredData.toArray(new KGXAddData[0]);
        if (filteredArray == null || filteredArray.length == 0) {
//            ToastUtils.show("添加成功");
            finish();
        } else {
            LLHttpManager.savedevicecollect(this, addData,controllerSerialNo,1, 4508, new HttpCallback<HttpData<Void>>(this){
                @Override
                public void onStart(Call call) {
                    showDialog();
                }
                @Override
                public void onSucceed(HttpData<Void> result) {
                    super.onSucceed(result);
                    getDeviceData();

                }
                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }



    }

    public void getDeviceData(){
        LLHttpManager.house_getdevices(new ApplicationLifecycle(), AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<List<DeviceBean>>>(this) {
            @Override
            public void onSucceed(HttpData<List<DeviceBean>> result) {
                super.onSucceed(result);
                LLDeviceDBManager.getInstance(getContext()).refreshAllDevicesTx( result.getData(), null);
                EventBus.getDefault().post(new RefreshDeviceListEvent());
                ToastUtils.show("添加成功");
                finish();
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }
}
